package com.badibadi.fragment;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONException;

import android.annotation.SuppressLint;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.badibadi.activity.CalendarMyActivityActivity;
import com.badibadi.adapter.ActivityMyActivityAdapter;
import com.badibadi.adapter.Popwindows_Adapter;
import com.badibadi.infos.Activity_Overview_Model;
import com.badibadi.infos.ClueTypeModel;
import com.badibadi.infos.Results;
import com.badibadi.mytools.Constants;
import com.badibadi.mytools.Dialog;
import com.badibadi.mytools.JSONUtils;
import com.badibadi.mytools.MySharePreferences;
import com.badibadi.mytools.MyThreadTool;
import com.badibadi.mytools.Utils;
import com.badibadi.uniclubber.R;
import com.libjph.util.StringUtil;
import com.view.my_view.XListView;
import com.view.my_view.XListView.IXListViewListener;

public class ActivityMyActivityFragment0 extends BaseFragment implements
		IXListViewListener {
	static ActivityMyActivityFragment0 fragment0;
	private ActivityMyActivityAdapter x1Adapter;
	private XListView xListView1;
	private PopupWindow popup = null;
	private int Page;// 当前显示数据页数
	// private int Type;// 显示类型
	private List<Activity_Overview_Model> activity_Overview_Models;
	private int languageType = 0;
	private MySharePreferences preferences;
	private List<ClueTypeModel> clueTypeModels;
	private Popwindows_Adapter popwindows_Adapter;
	private ListView type_list;
	private Results results;
	private List<Activity_Overview_Model> list;
	private String uid = "26";// 用户id
	private String fid = "-1";// 朋友的id
	private int Type = 0;// 0最新 1 最火 2 自创
	private LinearLayout Keyword_Frame;
	// 查询关键字相关
	private String searchName = null;
	private String tid = null;// 活动类型id
	// 查询类别相关字
	private TextView tv_search;
	private LinearLayout ll_search;
	private boolean isReturnUp = true;// 按返回键是否回退关键字
	private String language_type = null;
	// 查询的文本框
	// AutoCompleteTextView index_autocomplete_txt_view;
   
	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				try {
					Utils.ExitPrgress(getActivity());
					Utils.showMessage(getActivity(),
							getResources().getString(R.string.l_net_error));
					xListView1.stopRefresh();
					xListView1.stopLoadMore();
					xListView1.setRefreshTime(""+getResources().getString(R.string.ganggang));
				
				} catch (Exception e) {
				}

				break;
			case 2:
				try {
					Utils.ExitPrgress(getActivity());
					activity_Overview_Models.addAll(list);
					x1Adapter.notifyDataSetChanged();
					xListView1.stopRefresh();
					xListView1.stopLoadMore();
					xListView1.setRefreshTime(""+getResources().getString(R.string.ganggang));
				
				} catch (Exception e) {
				}

				break;
			case 3:
				try {
					Utils.ExitPrgress(getActivity());
					Utils.showMessage(getActivity(),
							getResources().getString(R.string.l_xa10));
					xListView1.stopRefresh();
					xListView1.stopLoadMore();
					xListView1.setRefreshTime(""+getResources().getString(R.string.ganggang));
				
				} catch (Exception e) {
				}

				break;
			case 4:// popwindow 类别操作

				try {
					Utils.ExitPrgress(getActivity());
					popwindows_Adapter = new Popwindows_Adapter(clueTypeModels,
							getActivity());
					type_list.setAdapter(popwindows_Adapter);
					type_list.setOnItemClickListener(new OnItemClickListener() {

						@Override
						public void onItemClick(AdapterView<?> arg0, View view,
								int position, long arg3) {
							tid = clueTypeModels.get(position).getId();
							tv_search.setVisibility(View.VISIBLE);
							ll_search.setVisibility(View.GONE);
							tv_search.setText(clueTypeModels.get(position)
									.getName());
							Page = 1;
							activity_Overview_Models.clear();
							x1Adapter.notifyDataSetChanged();
							Activity(Type, Page);
							if (popup != null) {
								popup.dismiss();
							}
						}
					});
				} catch (Exception e) {
				}

				break;

			default:
				break;
			}
		}
	};
	private LinearLayout acticity_overview0_btn_type;

	@SuppressLint("NewApi")
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		uid = getArguments().getString("uid", "26");
		fid = getArguments().getString("fid", "26");
		Type = getArguments().getInt("type", 0);

	}

	@Override
	public View onCreateView(final LayoutInflater inflater,
			ViewGroup container, Bundle savedInstanceState) {

		final View view = inflater.inflate(
				R.layout.activity_overview_importylayout, null);
		try {
			language_type = Dialog.getSystemLanguageTypegrzx(getActivity());
			tv_search = (TextView) view.findViewById(R.id.TheKeyword);
			ll_search = (LinearLayout) view.findViewById(R.id.seach_ll);
			Keyword_Frame = (LinearLayout) view
					.findViewById(R.id.Keyword_Frame);
			Page = 0;
			clueTypeModels = new ArrayList<ClueTypeModel>();
			activity_Overview_Models = new ArrayList<Activity_Overview_Model>();
			x1Adapter = new ActivityMyActivityAdapter(activity_Overview_Models,
					getActivity(), Type);
			preferences = new MySharePreferences(getActivity(), "language");
			languageType = preferences.get("language", 0);
		} catch (Exception e) {
		}
		InitMyXListView1(view);
		acticity_overview0_btn_type = (LinearLayout) view
				.findViewById(R.id.fragment_club_overview0_btn_type);
		Keyword_Frame.setVisibility(View.GONE);

		acticity_overview0_btn_type
				.setOnClickListener(new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						OpenOrClosePopWindows(inflater, v);
					}
				});

		return view;
	}

	/**
	 * 访问网络：显示活动
	 * 显示我的活动
	 * @param type
	 * @param page
	 */
	private void Activity(final int type, final int page) {
		MyThreadTool.fixedThreadPool.execute(new Runnable() {
			@Override
			public void run() {
				list = new ArrayList<Activity_Overview_Model>();
				Map<String, Object> map = new HashMap<String, Object>();
				try {
					map.put("languageType", language_type);
					map.put("uid", uid);
					map.put("type", type);//表示的最新，最火，附近
					if (!StringUtil.isNullOrEmpty(searchName)) {
						map.put("searchName", searchName);
					}
					if (tid != null) {
						map.put("tid", tid);
					}
					map.put("page", page);
					map.put("pageNum", 6);
				} catch (Exception e) {
				}
System.out.println(map);
//				   
				//    
				// + "page=" + page);
				//    ("我的活动列表提交的数据是:" + map.toString());
				String actcontent = Utils.sendRequest(map, Constants.BadiUrl
						+ "activity");
				if (actcontent != null) {
//					   
					results = Utils.checkResult_NNN(getActivity(), actcontent);
					//    ("我的活动列表数据返回是:" + actcontent);
					if (results != null && !results.getRetmsg().equals("null")) {
						try {
							list = JSONUtils.getListByJsonString(
									results.getRetmsg(),
									Activity_Overview_Model.class);
							System.out.println("results"+results.getRetmsg());
							mHandler.sendEmptyMessage(2);
						} catch (JSONException e) {
							   
						}
					} else {
						if (page > 1) {
							--Page;
						} else {
							Page = 1;
						}
						mHandler.sendEmptyMessage(3);
					}
				} else {
					if (page > 1) {
						--Page;
					} else {
						Page = 1;
					}
					mHandler.sendEmptyMessage(1);
				}
			}
		});
		
		
	}

	/**
	 * 显示种类
	 */
	private void hadType() {
		Utils.showPrgress(getActivity());
		MyThreadTool.fixedThreadPool.execute(new Runnable() {
			@Override
			public void run() {
				Map<String, Object> map = new HashMap<String, Object>();
				try {
					map.put("languageType", language_type);
					map.put("uid", Utils.getUid(getActivity()));
					map.put("type", "2");
					map.put("cid", "0");
				} catch (Exception e) {
				}
//				   
				String acticontent = Utils.sendRequest(map, Constants.BadiUrl_1
						+ "commonality/hadType");
				System.out.println("wodehuodong"+acticontent);
				if (acticontent != null) {
					Results results = Utils.checkResult_NNN(getActivity(),
							acticontent);
//					   
					if (results != null && results.getRetmsg() != null
							&& results.isRet()) {
						//    ("我的活动的类别结果是:" + acticontent);
						try {
							clueTypeModels = JSONUtils.getListByJsonString(
									results.getRetmsg(), ClueTypeModel.class);
							
							mHandler.sendEmptyMessage(4);
						} catch (JSONException e) {
							   
						}
					} else {
						mHandler.sendEmptyMessage(3);
					}
				} else {
					mHandler.sendEmptyMessage(1);
				}
			}
		});
		
	}

	/**
	 * 打开或管理悬浮对话框
	 * 
	 * @param inflater
	 * @param v
	 */
	public void OpenOrClosePopWindows(LayoutInflater inflater, View v) {

		View root = inflater.inflate(
				R.layout.fragment_club_overview_popwindows, null);
		popup = new PopupWindow(root, LinearLayout.LayoutParams.MATCH_PARENT,
				LinearLayout.LayoutParams.WRAP_CONTENT);
		type_list = (ListView) root.findViewById(R.id.type_list);
		popup.setBackgroundDrawable(new BitmapDrawable());
		popup.setFocusable(true);
		popup.setTouchable(true);
		popup.setOutsideTouchable(true);
		hadType();
		popup.showAsDropDown(v);

	}

	public void InitMyXListView1(View view) {
		xListView1 = (XListView) view
				.findViewById(R.id.after_landing_friends00_xlistView2);
		// xListView1.setDividerHeight(10);
		xListView1.setPadding(10, 10, 10, 10);
		xListView1.setXListViewListener(this);
		xListView1.setPullLoadEnable(true);
		xListView1.setPullRefreshEnable(true);
		xListView1.setAdapter(x1Adapter);
		// xListView1.startRefresh();
		xListView1.startLoadMore();
	}

	// @Override
	// public void onListViewRefresh() {
	// Page = 1;
	// // activity_Overview_Models = new ArrayList<Activity_Overview_Model>();
	// Activity_show(Type, Page);
	// }
	//
	// @Override
	// public void onListViewLoadMore() {
	// Utils.showPrgress(getActivity());
	// Activity_show(Type, ++Page);
	// }

	public static ActivityMyActivityFragment0 getInstance() {
		if (fragment0 == null) {
			return new ActivityMyActivityFragment0();
		}
		return fragment0;
	}

	@Override
	public void onRefresh() {
		Page = 1;
		activity_Overview_Models.clear();
		Activity(Type, Page);
	}

	@Override
	public void onLoadMore() {
		Activity(Type, ++Page);
	}

	/**
	 * 获取list中的数据（接口回调）
	 * 
	 * @param list
	 */
	public void getList(GetList list) {
		list.getList(activity_Overview_Models);
	}

	/**
	 * 点击回退键之后的操作回退到上一级
	 * 
	 * @param get
	 */
	public void getSearchIsReturnUp(getFragmentData get) {
		get.getIsReturnUp(isReturnUp);
		//    ("状态为:" + ll_search.getVisibility());
		if (ll_search.getVisibility() == 8) {// 隐藏
			//    ("隐藏状态，变为显示");
			// searchName = null;
			ll_search.setVisibility(View.VISIBLE);
			tv_search.setVisibility(View.GONE);
			Page = 1;
			tid = null;
			activity_Overview_Models.clear();
			x1Adapter.notifyDataSetChanged();
			Activity(Type, Page);
			//    ("返回类别");
		} else {
			try {
				//    ("退出");
				((getActivity())).finish();
				getActivity().overridePendingTransition(R.anim.slide_left2,
						R.anim.slide_right2);
			} catch (Exception e) {
			}

		}
	}

	public interface getFragmentData {
		// 是否返回到上一级returnSearch
		void getIsReturnUp(boolean isReturn);
	}

	/**
	 * 在activity中调用fragment的方法,隐藏或者可见EditText文本框和种类的button
	 */
	public void GoneOrVisibleEditTextandTypeButton(View view,
			boolean EditTextandroidTypeButtonisCanSee) {
		// CalendarMyActivityActivity.
		LinearLayout ll = (LinearLayout) view.findViewById(R.id.seach_ll);
		if (EditTextandroidTypeButtonisCanSee == false) {
			((CalendarMyActivityActivity) (getActivity()))
					.GoneOrVisibleSearchEdiTText(ll, -1);
			tv_search.setVisibility(View.VISIBLE);
		} else {
			((CalendarMyActivityActivity) (getActivity()))
					.GoneOrVisibleSearchEdiTText(ll, 1);
			tv_search.setVisibility(View.GONE);
		}
	}
	

	public interface GetList {
		void getList(List<Activity_Overview_Model> list);
	}

}
